import { useMemberStore } from '@/stores'

console.log(useMemberStore(), '123')

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// token
const memberStore = useMemberStore()
const options = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }

    // 请求超时时间
    options.timeout = 10000

    // 请求头
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }

    console.log(memberStore, 'memberStore')

    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}

uni.addInterceptor('request', options)
uni.addInterceptor('uploadFile', options)

interface Data<T> {
  code: string
  msg: string
  result: T
}

export const http = <T>(options: any) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success(res: any) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          // 没有权限
          memberStore.clearProfile()
          uni.showToast({ title: res.data.msg })
          reject(res)
          uni.navigateTo({
            url: 'pages/login/login',
          })
        } else {
          reject(res)
          uni.showToast({
            icon: 'none',
            title: res.data.msg || '获取数据失败',
          })
        }
      },
      fail() {
        uni.showToast({
          title: '网络错误',
        })
      },
    })
  })
}
